import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import * as storage from "@/utils/storage";
import site from "./modules/site";
import product from "./modules/product";
import * as types from "./types";
import { auth, logout } from "../api";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: {},
  },
  mutations: {
    [types.SET_USER](state, user) {
      state.user = user;
    },
  },
  actions: {
    async login({ commit }, data) {
      try {
        const { token, user } = await auth(data);
        commit(types.SET_USER, user);
        storage.set("z-admin-token", token);
      } catch (e) {
        return Promise.reject(e);
      }
    },
    async logout({ commit }) {
      try {
        await logout();
        commit(types.SET_USER, {});
        storage.remove("z-admin-token");
      } catch (e) {
        return Promise.reject(e);
      }
    },
  },
  modules: { site, product },
  plugins: [
    createPersistedState({
      key: "z-admin-store", // 设置保存在localstorage中的vuex数据的名称
      storage: {
        // 重写getItem等方法以使用secureLs进行本地存储
        getItem: (key) => storage.get(key),
        setItem: (key, value) => storage.set(key, value),
        removeItem: (key) => storage.remove(key),
      },
    }),
  ],
});
